package com.yonyou.cyxdms.sysmanage.client.service.login;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yonyou.cyx.framework.bean.dto.framework.RestResultResponse;
import com.yonyou.cyx.framework.compent.redis.RedisClient;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyx.function.utils.jsonserializer.JSONUtil;
import com.yonyou.cyxdms.framework.bean.dto.push.PushDTO;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.sysmanage.client.constants.BaseDataCommonConstants;
import com.yonyou.cyxdms.sysmanage.client.constants.BaseDataDictConstants;
import com.yonyou.cyxdms.sysmanage.client.domains.dto.EmployeeDictDto;
import com.yonyou.cyxdms.sysmanage.client.domains.dto.UserAndRoleDTO;
import com.yonyou.cyxdms.sysmanage.client.domains.dto.UserDictDto;
import com.yonyou.cyxdms.sysmanage.client.feign.SysmanageDataCommonClient;
import com.yonyou.cyxdms.sysmanage.client.vo.advice.AdviceRuleVO;
import com.yonyou.cyxdms.sysmanage.client.vo.company.CompanyDealerAscVO;
import com.yonyou.cyxdms.sysmanage.client.vo.company.CompanyOrgMaintenanceTreeVO;
import com.yonyou.cyxdms.sysmanage.client.vo.company.CompanyOrgVO;
import com.yonyou.cyxdms.sysmanage.client.vo.company.CompanyVO;
import com.yonyou.cyxdms.sysmanage.client.vo.dealer.DealerInfoParentVO;
import com.yonyou.cyxdms.sysmanage.client.vo.dealer.DealerOrgAreaVO;
import com.yonyou.cyxdms.sysmanage.client.vo.dealer.DealerPictureVO;
import com.yonyou.cyxdms.sysmanage.client.vo.employee.EmployeeVO;
import com.yonyou.cyxdms.sysmanage.client.vo.org.OrgAndParentVO;
import com.yonyou.cyxdms.sysmanage.client.vo.org.OrgParentVO;
import com.yonyou.cyxdms.sysmanage.client.vo.user.UserInfoVO;

/**
 * 品牌信息
 *
 * @author: renwd
 * @since: 2018/11/27
 * @version:1.0 Copyright: Copyright (c) 2018
 */

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    RedisClient redisClient;
    @Autowired
    SysmanageDataCommonClient sysmanageDataCommonClient;
    //日志对象
    private static final Logger logger = LoggerFactory.getLogger(LoginServiceImpl.class);

    /**
     * 通过userId获取user对象
     *
     * @param userId
     * @return UserInfoDto
     * @author maxingjian
     * @date 2019年08月13日
     */
    @Override
    public UserDictDto getUserById(Long userId) {
        Object userDictDto = getFromRedis(BaseDataCommonConstants.USER_CACHE_USERID, userId.toString());
        if (null != userDictDto) {
            return JSONUtil.jsonToObj(JSONUtil.objectToJson(userDictDto), UserDictDto.class);
        } else {
            return sysmanageDataCommonClient.getUserById(userId).getData();
        }
    }

    @Override
    public UserDictDto getUserByIdCMS(Long userId) {
        Object userDictDto = getFromRedis(BaseDataCommonConstants.USER_CACHE_USERID_CMS, userId.toString());
        if (null != userDictDto) {
            return JSONUtil.jsonToObj(JSONUtil.objectToJson(userDictDto), UserDictDto.class);
        } else {
            return sysmanageDataCommonClient.getUserByIdCMS(userId).getData();
        }
    }

    /**
     * 通过userIds获取user集合对象
     *
     * @param userIds
     * @return List<UserDictDto>
     * @author wy
     * @date 2020年04月18日
     */
    @Override
    public List<UserDictDto> getUserListByIds(List<Long> userIds) {
    	if(userIds!=null &&userIds.size()>0) {
    		List<UserDictDto> userList = new ArrayList<UserDictDto>();
    		for(Long userId : userIds) {
    			Object userDictDto = getFromRedis(BaseDataCommonConstants.USER_CACHE_USERID, userId.toString());
    	        if (null != userDictDto) {
    	        	userList.add(JSONUtil.jsonToObj(JSONUtil.objectToJson(userDictDto), UserDictDto.class));
    	        } else {
    	        	userList.add(sysmanageDataCommonClient.getUserById(userId).getData());
    	        }
    		}
    		return userList;
    	}else {
    		return null;
    	}
    }

    /**
     * 通过userId获取Employee对象
     *
     * @param employeeId
     * @return UserInfoDto
     * @author maxingjian
     * @date 2019年08月13日
     */
    @Override
    public EmployeeDictDto getEmployeeById(Long employeeId) {

        Object employeeDictDto = getFromRedis(BaseDataCommonConstants.EMPLOYEE_CACHE_EMPLOYEEID, employeeId.toString());
        if (null != employeeDictDto) {
            return JSONUtil.jsonToObj(JSONUtil.objectToJson(employeeDictDto), EmployeeDictDto.class);
        } else {
            return sysmanageDataCommonClient.getEmployeeById(employeeId).getData();
        }
    }

    /**
     * 通过条件查询返回sql语句
     *
     * @param menuId
     * @param alias
     * @param orgColumn
     * @param salesColumn
     * @return String
     * @author maxingjian
     * @date 2019年08月13日
     */
    @Override
    public String getQueryScope(Long menuId, String alias, String orgColumn, String salesColumn) {
        return getQueryScope(menuId, alias, orgColumn, salesColumn,false);
    }

    @Override
    public String getQueryScope(Long menuId, String alias, String orgColumn, String salesColumn, boolean isDealer)
    {
        return getQueryScope(menuId, alias, orgColumn, salesColumn,false,false,false);
    }

    /**
     * 通过条件查询返回sql语句
     *
     * @param menuId
     * @param alias
     * @param orgColumn
     * @param salesColumn
     * @return String
     * @author maxingjian
     * @date 2019年08月13日
     */
    @Override
    public String getQueryScope(Long menuId, String alias, String orgColumn, String salesColumn,boolean isDealer,boolean needSaleCode,boolean needServiceCode)
    {
        StringBuffer str = new StringBuffer();
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        if (menuId == null) {
                 str.append(" and ").append((StringUtils.isNullOrEmpty(alias) ? " " : alias + ".")).append("APP_ID = '").append(loginInfoDto.getAppId() + "' " );
                 if (loginInfoDto.getDataType().toString().equals(String.valueOf(BaseDataDictConstants.DATA_TYPE_BY_OWNER))) {
                     if (isDealer) {
                         str.append(" and ").append((StringUtils.isNullOrEmpty(alias) ? " " : alias + ".") + "OWNER_CODE = '" + loginInfoDto.getOwnerCode() + "' ");
                     } else {
                         str.append(" and ").append((StringUtils.isNullOrEmpty(alias) ? " " : alias + ".") + "OWNER_CODE IN ('" + loginInfoDto.getOwnerCode() + "','-1','" + loginInfoDto.getGroupCode() + "') ");
                     }
                 }

        } else {
            str.append(sysmanageDataCommonClient.findAuthorization(menuId, alias, salesColumn, orgColumn,isDealer,needSaleCode,needServiceCode).getData());
            if (StringUtils.isNullOrEmpty(str)) {
                str.append(" and ").append((StringUtils.isNullOrEmpty(alias) ? " " : alias + ".") + "APP_ID = '" + loginInfoDto.getAppId() + "' ") ;
                if (loginInfoDto.getDataType().toString().equals(String.valueOf(BaseDataDictConstants.DATA_TYPE_BY_OWNER))) {
                    if (isDealer) {
                        str.append(" and ").append((StringUtils.isNullOrEmpty(alias) ? " " : alias + ".") + "OWNER_CODE = '" + loginInfoDto.getOwnerCode() + "' ");
                    } else {
                        str.append(" and ").append((StringUtils.isNullOrEmpty(alias) ? " " : alias + ".") + "OWNER_CODE IN ('" + loginInfoDto.getOwnerCode() + "','-1','" + loginInfoDto.getGroupCode() + "') ");
                    }
                }
            }
        }
        return str.toString();
    }


    @Override
    public String findPermissionRangeByMenu(Long menuId) {
        return sysmanageDataCommonClient.findPermissionRangeByMenu(menuId).getData();
    }

    @Override
    public String getQueryScope() {
        return getQueryScope(null);
    }

    @Override
    public String getQueryScope(String alias) {
        return getQueryScope(null, alias, null, null);
    }

    @Override
    public RestResultResponse<Map<String, Object>> getRoles(String userId) {
        return sysmanageDataCommonClient.getRoles(userId);
    }


    @Override
    public String pushByUserIdOrEmpNo(PushDTO pushDTO) {
        return sysmanageDataCommonClient.pushByUserIdOrEmpNo(pushDTO).getData();
    }

    public Object getFromRedis(String messageFormat, String Id) {
        Object object = redisClient.hget(messageFormat, Id);
        return object;
    }


    @Override
    public List<EmployeeVO> getEmployeeNoByLikeEmployeeName(String appId, String ownerCode, String employeeName) {
        Object employeeVO = redisClient.get(BaseDataCommonConstants.USER_CACHE_USERID);
        if (null == employeeVO) {
            // 查询所有数据
            // loadValueIfNotExists();
            Object redisregionDto = redisClient.get(BaseDataCommonConstants.USER_CACHE_USERID);
            if (null == redisregionDto) {
                return null;
            }
            return JSONUtil.jsonToList(JSONUtil.objectToJson(redisregionDto), EmployeeVO.class);
        } else {
            return JSONUtil.jsonToList(JSONUtil.objectToJson(employeeVO), EmployeeVO.class);
        }
    }


    /**
     * 根据角色类别获取用户信息
     *
     * @param role 角色类别
     * @return
     * @author 李贺
     * @since 2019/9/9
     */
    @Override
    public List<UserAndRoleDTO> getUserListByRole(Integer role) {
        RestResultResponse<List<UserAndRoleDTO>> userListByRole = sysmanageDataCommonClient.getUserListByRole(role);
        return userListByRole.getData();
    }


    /**
     * 获取登录用户组织信息
     *
     * @auther: 李贺
     * @since: 2019/9/9
     */
    @Override
    public OrgAndParentVO getOrg(String orgId) {
    	 //CMS-缓存组织信息
    	 Object orgAndParentVO = redisClient.hget(BaseDataCommonConstants.ORG_CACHE_ORGID,orgId);
    	 if (null == orgAndParentVO) {
    		 OrgAndParentVO newOrgAndParentVO = sysmanageDataCommonClient.getOrg(orgId).getData();
    		 redisClient.hsetExpire(BaseDataCommonConstants.ORG_CACHE_ORGID,
    				 orgId,
    				 JSONUtil.objectToJson(newOrgAndParentVO),
    				 BaseDataCommonConstants.EXPIRE_TIME_ONE_DAY);
             return newOrgAndParentVO;
         } else {
             return JSONUtil.jsonToObj(JSONUtil.objectToJson(orgAndParentVO), OrgAndParentVO.class);
         }
        //return sysmanageDataCommonClient.getOrg(orgId).getData();
    }

    @Override
    public Void pushBy(String title, Integer templateCode, Integer userIds, Map<String, Object> templateContentMap) {
        return sysmanageDataCommonClient.pushBy(title, templateCode, userIds,null, templateContentMap).getData();
    }

    @Override
    public Void pushBys(Integer kind, Integer businessId, String orderID, String recordVersion, String actionId, String clueId, String clueType,
                        String customerBusinessId, String dataType, String title, Integer templateCode, Integer userIds, Map<String, Object> templateContentMap) {
        return sysmanageDataCommonClient.pushBys(kind, businessId, orderID, recordVersion, actionId, clueId, clueType, customerBusinessId, dataType, title, templateCode, userIds, templateContentMap).getData();
    }

    @Override
    public Void pushBysZHT(Integer kind, Integer businessId, String orderID, String recordVersion, String actionId, String clueId, String clueType,
                        String customerBusinessId, String dataType, String title, Integer templateCode, Integer userIds,String jwt, Map<String, Object> templateContentMap) {
        return sysmanageDataCommonClient.pushBysZHT(kind, businessId, orderID, recordVersion, actionId, clueId, clueType, customerBusinessId, dataType, title, templateCode, userIds,jwt, templateContentMap).getData();
    }

    /**
     * 新增公司
     *
     * @auther: 李贺
     * @since: 2019/9/12
     */
    @Override
    public CompanyDealerAscVO addDealerCompany(CompanyDealerAscVO companyDealerAscVO) {
        return sysmanageDataCommonClient.addDealerCompany(companyDealerAscVO).getData();
    }

    /**
     * 新增多个公司
     *
     * @author 李贺
     * @since 2019/12/2
     */
    @Override
    public List<CompanyDealerAscVO> addDealerCompanyList(List<CompanyDealerAscVO> companyDealerAscVOList) {
        return sysmanageDataCommonClient.addDealerCompanyList(companyDealerAscVOList).getData();
    }

    /**
     * 更新接口，更新公司表、经销商表、服务站表
     *
     * @author 李贺
     * @since 2019/9/12
     */
    @Override
    public CompanyDealerAscVO updateDealerCompany(CompanyDealerAscVO companyDealerAscVO) {
        return sysmanageDataCommonClient.updateDealerCompany(companyDealerAscVO).getData();
    }


    @Override
    public List<AdviceRuleVO> findAdviceRules(String paramCode) {
        return sysmanageDataCommonClient.findAdviceRules(paramCode).getData();
    }

    @Override
    public CompanyVO getCompany(Long companyId) {
        return sysmanageDataCommonClient.getCompany(companyId).getData();
    }

    @Override
    public Integer getAppPosition() {
        return sysmanageDataCommonClient.getAppPosition().getData();
    }

    @Override
    public List<UserInfoVO> getUsersByPosition(Long menuId, List<Integer> positionCodes, String userPhone) {
        return sysmanageDataCommonClient.getUsersByPosition(menuId, positionCodes, userPhone).getData();
    }

    /**
     * 根据条件查询经销商信息
     *
     * @auther: 李贺
     * @since: 2019/11/13
     */
    @Override
    public List<DealerInfoParentVO> getDealerInfos(Long orgId, Long provinceId) {
        return sysmanageDataCommonClient.getDealerInfos(orgId, provinceId).getData();
    }

    /**
     * 查询用户职位
     * 李贺
     */
    @Override
    public List<Integer> getPositions(Long userId) {
        return sysmanageDataCommonClient.getPositions(userId).getData();
    }

    /**
     * 根据省市区查询经销商信息
     *
     * @auther: 李贺
     * @since: 2019/11/15
     */
    @Override
    public List<DealerInfoParentVO> getDealerByCity(Integer provinceId, Integer cityId, Integer countyId) {
        return sysmanageDataCommonClient.getDealerByCity(provinceId, cityId, countyId).getData();
    }

    @Override
    public List<UserInfoVO> getUserByOrgId(String orgId) {
        return sysmanageDataCommonClient.getUserByOrgId(orgId).getData();
    }

    /**
     * 获得所有经销商信息
     *
     * @auther: 李贺
     */
    @Override
    public List<DealerInfoParentVO> getAllDealer(String orgId) {
        return sysmanageDataCommonClient.getAllDealer(orgId).getData();
    }

    /**
     * 获取所有事业部
     *
     * @return
     * @author 李贺
     * @since 2019/11/25
     */
    @Override
    public List<OrgParentVO> getBusinessOrg() {
        return sysmanageDataCommonClient.getBusinessOrg().getData();
    }

    /**
     * 获得当前车厂的信息
     *
     * @return: 获得当前车厂的信息
     * @auther: 李贺
     * @since: 2019/11/26
     */
    @Override
    public CompanyVO factoryCompany() {
        return sysmanageDataCommonClient.factoryCompany().getData();
    }

    /**
     * 根据userName获得userId
     */
    @Override
    public List<Long> getUserIdByName(String appId, String ownerCode, String name) {
        return sysmanageDataCommonClient.getUserIdByName(appId, ownerCode, name).getData();
    }

    /**
     * 车厂通过组织id（大区小区类型的组织）获取本车厂下对应的经销商
     *
     * @param orgId
     * @param:
     * @return: 车厂通过组织id（大区小区类型的组织）获取本车厂下对应的经销商
     * @auther: 马邢健
     * @since: 2019/10/31
     */
    @Override
    public List<DealerOrgAreaVO> getDealerBySaleArea(String orgId, String dealerCode, String dealerName) {
        return sysmanageDataCommonClient.getDealerBySaleArea(orgId, dealerCode, dealerName).getData();
    }

    /**
     * 根据组织id 获得组织信息
     *
     * @auther: 李贺
     * @since: 2019/12/6
     */
    @Override
    public List<OrgParentVO> getOrgByOrgIds(String orgIds) {
        return sysmanageDataCommonClient.getOrgByOrgIds(orgIds).getData();
    }

    /**
     * 获取树状图
     *
     * @author 李贺
     * @since 2019/12/12
     */
    @Override
    public List<CompanyOrgMaintenanceTreeVO> getOrgs() {
        return sysmanageDataCommonClient.getOrgs().getData();
    }


    /**
     * 获取树状图
     *
     * @author 李贺
     * @since 2019/12/12
     */
    @Override
    public List<CompanyOrgMaintenanceTreeVO> getDrlOrgs() {
        return sysmanageDataCommonClient.getDrlOrgs().getData();
    }
    /**
     * 获取车厂所有组织
     *
     * @author zys
     * @since 2020/02/05
     */
    @Override
    public List<CompanyOrgVO> getOrgsNoCompanyId() {
        return sysmanageDataCommonClient.getOrgsNoCompanyId().getData();
    }
    /**
     * 获得经销商所属区域
     * 李贺
     *
     * @param
     * @return
     */
    @Override
    public List<OrgParentVO> getSaleArea(List<Long> dealerIds) {
        return sysmanageDataCommonClient.getSaleArea(dealerIds).getData();
    }

    /**
     * 获取经销商营业时间和门店图片
     * dealerIds 逗号隔开
     * dealerCodes 逗号隔开
     * <p>
     * 李贺
     */
    @Override
    public List<DealerPictureVO> getDealerPictures(String dealerIds, String dealerCodes) {
        return sysmanageDataCommonClient.getDealerPictures(dealerIds,dealerCodes).getData();
    }
}
